package com.zhuozhou.jdyc.base;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;

import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * Create by CherishTang on 2019/8/1
 * describe:解析接口统一返回数据
 */
public class BaseResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private final Gson gson;
    private final TypeAdapter<T> adapter;

    BaseResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
        this.gson = gson;
        this.adapter = adapter;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {

        String jsonString = value.string();
        try {
            BaseModelEntity baseModel = new GsonBuilder().disableHtmlEscaping().create().fromJson(jsonString,
                    new TypeToken<BaseModelEntity<T>>() {
                    }.getType());
            if (!"0".equals(baseModel.getCode())) {
                throw new BaseException(baseModel.getMsg(), baseModel.getCode());
            }
            return adapter.fromJson(new Gson().toJson(baseModel.getData() == null ? "操作完成" : baseModel.getData()));
        } catch (Exception e) {
            try {
                //数据解析异常
                T baseModel = new GsonBuilder().disableHtmlEscaping().create().fromJson(jsonString,
                        new TypeToken<T>() {
                        }.getType());
                return adapter.fromJson(new Gson().toJson(baseModel == null ? "操作完成" : baseModel));
            } catch (Exception x) {
                x.printStackTrace();
                //数据解析异常
                throw x;
            }
        } finally {
            value.close();
        }
    }
}
